﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace Needle.Bus.Transport.Impl.LoopBack
{
    public class LoopBackTransport  : CommunicationObject, ITransport 
    {

        public LoopBackTransport()
        {
            _Extensions = new ExtensionCollection<ITransport>(this, ThisLock);
        }

        #region ITransport Members

        public IChannel<T> OpenChannel<T>(string topic)
        {
            foreach (IChannel<T> channel in Extensions.FindAll<IChannel<T>>())
                if (channel.Topic == topic)
                    return channel;

            var loopBackChannel = new LoopBackChannel<T>(topic);
            Extensions.Add(loopBackChannel);
            return loopBackChannel;
        }

        public void RegisterEndPoint<T>(IEndPoint<T> endPoint)
        {
            Extensions.Add(endPoint);
        }
        public void UnregisterEndPoint<T>(IEndPoint<T> endPoint)
        {
            Extensions.Remove(endPoint);
        }
        #endregion

        #region IExtensibleObject<ITransport> Members

        private ExtensionCollection<ITransport> _Extensions;
        public IExtensionCollection<ITransport> Extensions
        {
            get { return _Extensions; }
        }

        #endregion

        protected override TimeSpan DefaultCloseTimeout
        {
            get { return TimeSpan.FromMinutes(1); }
        }

        protected override TimeSpan DefaultOpenTimeout
        {
            get { return TimeSpan.FromMinutes(1); }
        }

        protected override void OnAbort()
        {
             
        }

        protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return null;
        }

        protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return null;
        }

        protected override void OnClose(TimeSpan timeout)
        {
            Extensions.Clear();
        }

        protected override void OnEndClose(IAsyncResult result)
        {
            
        }

        protected override void OnEndOpen(IAsyncResult result)
        {
          
        }

        protected override void OnOpen(TimeSpan timeout)
        {
            
        }
    }   
}
